﻿using Core.DTO.System.SysPerson;
using Core.IRepository;
using Core.IService;
using Core.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Core.Service
{
    public partial class SysPersonService : BaseService<SysPerson>, ISysPersonService
    {

        public async Task<TokenDTO> Login(string LoginName,string LoginPwd)
        {
            var result = await baseRepostory.Find<SysPerson>(p => p.LoginName == LoginName && p.LoginPwd == LoginPwd)
                .Include("Roles")
                .Select(p => new TokenDTO()
                {
                    Id = p.Id,
                    Name = p.Name,
                    OrgId = p.OrgId,
                    Role = string.Join(',', p.Roles.Select(r => r.Name).ToArray())
                }).FirstOrDefaultAsync();
            return result;
        }

        public List<SysPersonListDTO> GetList(int? orgId, string name, int pageSize, int pageIndex,out int total)
        {
            Expression<Func<SysPerson, bool>> exp = p => p.Name.Contains(name);
            if (orgId.HasValue)
                exp = p => p.OrgId == orgId.Value;

            var list = baseRepostory.Find<SysPerson, int>(pageIndex, pageSize, exp, p => p.Id, out total)
                .Include("Org")
                .Include("Roles")
                .Select(p => mapper.Map<SysPersonListDTO>(p))
                .ToList();
            return list;
        }
    }
}
